package com.geekcode.wol.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.Charset;

public class Wol {

	public static boolean wake(String mac, String ip){
		boolean flag = false;
		flag = wakeOnPackage(mac, ip)|| flag;
		flag = wakeOnLinux(mac, ip) || flag;
		return flag;
	}
	
	public static boolean wakeOnPackage(String mac, String ip){
		if(ip == null){
			ip = "255.255.255.255";
		}
        int port = 9;//端口号
        String[] ips = mac.toUpperCase().split("\\:|\\-");
        byte[] macByte = new byte[6];
		for (int i = 0; i < 6; i++) {
			macByte[i] = (byte) Integer.parseInt(ips[i], 16);
		}
		byte[] bys = new byte[6 + 16 * macByte.length];
		for (int i = 0; i < 6; i++) {
			bys[i] = (byte) 0xff;
		}
		for (int i = 6; i < bys.length; i += macByte.length) {
			System.arraycopy(macByte, 0, bys, i, macByte.length);
		}
        try {
            InetAddress address = InetAddress.getByName(ip);
            MulticastSocket socket = new MulticastSocket(port);
            DatagramPacket packet = new DatagramPacket(bys, bys.length, address, port);
            socket.send(packet);
            socket.close();
            return true;
        } catch (Exception e) {
        	return false;
        }
	}
	
	public static boolean wakeOnLinux(String mac, String ip){
		mac = mac.replace("-", ":");
		StringBuffer buffer = new StringBuffer();
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("wakeonlan " + mac + " -i " + ip);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GB2312")));
            String inline;
            while ((inline = br.readLine()) != null) {
            	buffer.append(inline + "\r\n");
            }
            br.close();
        } catch (IOException e) {
        	 return true;
        }
        return false;
    }
}
